package com.cty.Stack;
/*
*
* 用栈实现计算器
* */
public class calculator {
    public static void main(String[] args) {
        //运算表达式
        String expression = "70*2+8";
        //创建两个栈一个用来放入数字，一个用来放入符号
        ArrayStack2 numStack = new ArrayStack2(10);//数字栈
        ArrayStack2 operatorStack = new ArrayStack2(10);//符号栈
        //扫描表达式用的索引
        int index = 0;
        //创建两个数字用于接受表达式中的数字
        int num1 = 0;
        int num2 = 0;
        //创建一个字符用于接收表达式中的符号
        char ch = ' ';
        //创建一个变量用于接收从符号栈弹出的符号
        int pre = 0;
        //用于接受最后的结果
        int res = 0;
        //用于解决两位数计算的问题
        String keepNum = "";
        //开始扫描表达式
        while (true) {
            //将字符串分割，再转成字符
            ch = expression.substring(index,index + 1).charAt(0);
            //判断是否为字符
            if (operatorStack.isOper(ch)) {
                //如果是字符的话，判断字符栈中是否为空
                if(!operatorStack.isEmpty()) {//不为空
                    //判断栈中字符与该字符的优先级大小
                    if (operatorStack.oper(ch) <= operatorStack.oper(operatorStack.peek())) {
                        pre = operatorStack.pop();
                        num1 = numStack.pop();
                        num2 = numStack.pop();
                        res = numStack.cal(num1, num2, pre);
                        numStack.push(res);
                        operatorStack.push(ch);
                    }else {
                        operatorStack.push(ch);
                    }
                }else{
                    operatorStack.push(ch);
                }
            }else {
                //首先判断index是否已经遍历到字符串的末尾
                if (index == expression.length() - 1) {
                    numStack.push(ch - 48);//ch 是'1' 而不是 1 相差48
                } else {
                    //利用字符串拼接的方法来解决
                    keepNum += ch;
                    //判断下一位是否为字符
                    if (operatorStack.isOper(expression.substring(index+1,index+2).charAt(0))) {
                        numStack.push(Integer.parseInt(keepNum));
                    } else {
                        index++;
                        ch = expression.substring(index,index+1).charAt(0);
                        keepNum += ch;
                        numStack.push(Integer.parseInt(keepNum));
                    }
                    //将keepNum制空
                    keepNum = "";
                }
            }
            //循环停止逻辑
            if (index >= expression.length()-1) {
                break;
            }
            //索引自增
            index++;
        }
        //栈中还有数据依次取出来计算
        while (true) {
            if (operatorStack.isEmpty()) {
                break;
            }
            num1 = numStack.pop();
            num2 = numStack.pop();
            pre = operatorStack.pop();
            res =numStack.cal(num1,num2,pre);
            numStack.push(res);
        }
        res = numStack.pop();
        //最终结果
        System.out.printf("结果：%s = %d",expression,res);
    }
}
